#include "QtOpenCvAddEmployee.h"




QtOpenCvAddEmployee::QtOpenCvAddEmployee(QWidget* parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    //人脸检测设置------------------------------------------------------------------
    //加载级联分类器
    if (faceCascade.load("D:/opencv/build/etc/haarcascades/haarcascade_frontalface_alt2.xml")) qDebug() << "级联分类器加载成功";
    numSubFace = 0;
    connect(&checkTimer, &QTimer::timeout,this, &QtOpenCvAddEmployee::faceDetector);
}

QtOpenCvAddEmployee::~QtOpenCvAddEmployee()
{
}

void QtOpenCvAddEmployee::closeEvent(QCloseEvent* event){//界面关闭时关闭定时器
    //关闭摄像头
    videoCap.release();
    checkTimer.stop();
}

void QtOpenCvAddEmployee::open() {//显示对话框自动开始人脸检测
    show();
    //打开摄像头
    videoCap.open(0);
    checkTimer.start(50);
}
void QtOpenCvAddEmployee::faceDetector() {//获取视频数据
    Mat videoFrame;
    if (videoCap.grab()) {//.grab()获取一个视频帧,并返回布尔型
        videoCap.read(videoFrame);//videoFrame获取这个帧
        if (!videoFrame.data)return;//空帧直接返回 
        cvtColor(videoFrame, videoFrame, cv::COLOR_BGR2RGB);
        QtOpenCvAddEmployee::checkFace(videoFrame);//调用人脸检测
        QImage image(videoFrame.data, videoFrame.cols, videoFrame.rows, static_cast<int>(videoFrame.step), QImage::Format_RGB888);
        ui.label->setPixmap(QPixmap::fromImage(image));
    }
}
void QtOpenCvAddEmployee::checkFace(cv::Mat videoFrame) {//人脸检测
    faceData = Mat();
    //将图片修改色度,以便检测
    Mat grayFrame;
    cvtColor(videoFrame, grayFrame, COLOR_BGR2GRAY);
    if (!grayFrame.data)return;
    //人脸检测
    std::vector<cv::Rect> faces;//人脸位置数据
    faceCascade.detectMultiScale(grayFrame, faces, 1.1, 3, 0, cv::Size(30, 30));
    //人脸数据获取
    if (faces.size() > 0) {
        // 绘制矩形框
        cv::rectangle(videoFrame, faces[0], cv::Scalar(0, 255, 0), 2);
        faceData = grayFrame(faces[0]).clone();
    }
}
void QtOpenCvAddEmployee::on_ackButton_clicked() {//保存身份与人脸信息
    //保存人脸到文件夹
    QDir Dir;
    Dir.mkpath(QString("EmployeeIdentificationForm\\FaceDatas\\%1").arg(ui.idEmployee->text()));
    //检查员工信息完整度
    if (ui.areaEmployee->text() == "" || ui.idEmployee->text() == "" || ui.nameEmployee->text() == "" || ui.positionEmployee->text() == "") {
        QMessageBox::information(this, "无法提交", "未填写员工信息");
        return;
    }
    //多重检查是否检测到人脸
    std::vector<cv::Rect> faces;//人脸位置数据
    faceCascade.detectMultiScale(faceData, faces, 1.1, 3, 0, cv::Size(30, 30));
    if (faces.size() <= 0) {
        QMessageBox::information(this, "保存失败", "未检测到人脸");
        try { imshow("错误人脸", faceData); }
        catch (cv::Exception e) { qDebug() << e.what(); }
        return;
    }
    switch (numSubFace) {
        default: {
            imwrite(QString("EmployeeIdentificationForm\\FaceDatas\\%1\\%2.jpg").arg(ui.idEmployee->text(), QString::number(numSubFace + 1)).toStdString(), faceData);
            ++numSubFace;
            if (numSubFace==8) {
                ui.ackButton->setText(QString("完成最后一个操作-%1").arg(QString::number(numSubFace + 1)));
            }
            else {
                ui.ackButton->setText(QString("确认-%1").arg(QString::number(numSubFace + 1)));
            }
            break;
        }
        case 8: {
            imwrite(QString("EmployeeIdentificationForm\\FaceDatas\\%1\\%2.jpg").arg(ui.idEmployee->text(), QString::number(numSubFace + 1)).toStdString(), faceData);
            numSubFace = 0;
            ui.ackButton->setText(QString("确认-%1").arg( QString::number(numSubFace + 1)));
            QtOpenCvAddEmployee::saveFace();
            break;
        }
    }

}
void QtOpenCvAddEmployee::saveFace() {
    //打开数据库
    QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName("EmployeeIdentificationForm/EmployeeIdentificationForm.db"); // 设置数据库文件名
    if (!database.open()) {
        QMessageBox::information(this, "保存失败", "数据库打开失败");
        qDebug() << database.lastError();
        return;
    }
    QSqlQuery query(database);//如果还未建表则创建
    //检查数据表创建问题
    if(!query.exec("CREATE TABLE IF NOT EXISTS employeeIdentificationForm("
        "ID INTEGER PRIMARY KEY AUTOINCREMENT," // 使用AUTOINCREMENT而不是AUTO_INCREMENT
        "employeeID INT NOT NULL,"
        "employeeArea TEXT NOT NULL," // VARCHAR在SQLite中对应TEXT类型
        "employeeName TEXT NOT NULL," // VARCHAR在SQLite中对应TEXT类型
        "employeePosition TEXT NOT NULL,"// VARCHAR在SQLite中对应TEXT类型
        "faceImage1 TEXT NOT NULL,"//人脸数据
        "faceImage2 TEXT NOT NULL,"
        "faceImage3 TEXT NOT NULL,"
        "faceImage4 TEXT NOT NULL,"
        "faceImage5 TEXT NOT NULL,"
        "faceImage6 TEXT NOT NULL,"
        "faceImage7 TEXT NOT NULL,"
        "faceImage8 TEXT NOT NULL,"
        "faceImage9 TEXT NOT NULL);")){//如果失败输出原因
        QMessageBox::information(this, "数据表创建失败", query.lastError().text());
    }
    // 然后，创建一个唯一索引
    query.exec("CREATE UNIQUE INDEX idx_employeeID ON employeeIdentificationForm (employeeID);");
    //插入员工信息
    query.prepare("INSERT INTO employeeIdentificationForm ("
        "employeeID, employeeArea, employeeName, employeePosition,faceImage1,faceImage2,faceImage3,faceImage4,faceImage5,faceImage6,faceImage7,faceImage8,faceImage9) "
        "VALUES (:employeeID, :employeeArea, :employeeName, :employeePosition, :faceImage1, :faceImage2, :faceImage3, :faceImage4, :faceImage5, :faceImage6, :faceImage7, :faceImage8, :faceImage9)");
    // 替换以下值以匹配你要插入的数据
    query.bindValue(":employeeID", ui.idEmployee->text()); // 假设的员工ID
    query.bindValue(":employeeArea", ui.areaEmployee->text()); // 假设的员工区域
    query.bindValue(":employeeName", ui.nameEmployee->text()); // 假设的员工姓名
    query.bindValue(":employeePosition", ui.positionEmployee->text()); // 假设的员工职位
    query.bindValue(":faceImage1", QString("EmployeeIdentificationForm/FaceDatas/%1/1.jpg").arg(ui.idEmployee->text())); //人脸数据
    query.bindValue(":faceImage2", QString("EmployeeIdentificationForm/FaceDatas/%1/2.jpg").arg(ui.idEmployee->text()));
    query.bindValue(":faceImage3", QString("EmployeeIdentificationForm/FaceDatas/%1/3.jpg").arg(ui.idEmployee->text()));
    query.bindValue(":faceImage4", QString("EmployeeIdentificationForm/FaceDatas/%1/4.jpg").arg(ui.idEmployee->text()));
    query.bindValue(":faceImage5", QString("EmployeeIdentificationForm/FaceDatas/%1/5.jpg").arg(ui.idEmployee->text()));
    query.bindValue(":faceImage6", QString("EmployeeIdentificationForm/FaceDatas/%1/6.jpg").arg(ui.idEmployee->text()));
    query.bindValue(":faceImage7", QString("EmployeeIdentificationForm/FaceDatas/%1/7.jpg").arg(ui.idEmployee->text()));
    query.bindValue(":faceImage8", QString("EmployeeIdentificationForm/FaceDatas/%1/8.jpg").arg(ui.idEmployee->text()));
    query.bindValue(":faceImage9", QString("EmployeeIdentificationForm/FaceDatas/%1/9.jpg").arg(ui.idEmployee->text()));
    if (!query.exec()) {//检查是否保存失败
        QMessageBox::information(this, "保存失败", "你的员工信息出现冲突");
    }
    database.close();
}